package com.jumi.microservice.stock;

import com.jumi.microservice.domain.GoodsStockDO;
import com.jumi.microservice.mapper.GoodsStockMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 商品库存更新命令的抽象基类
 *
 * @author Administrator
 */
public abstract class AbstractOrderStockUpdater implements StockUpdater {

    private static final Logger logger = LoggerFactory.getLogger(AbstractOrderStockUpdater.class);

    /**
     * 商品库存DO对象
     */
    protected List<GoodsStockDO> goodsStocks;

    /**
     * 商品库存管理模块的mapper组件
     */
    protected GoodsStockMapper goodsStockMapper;

    /**
     * 构造函数
     *
     * @param goodsStocks      商品库存DO对象
     * @param goodsStockMapper 商品库存管理模块的mapper组件
     */
    public AbstractOrderStockUpdater(List<GoodsStockDO> goodsStocks, GoodsStockMapper goodsStockMapper) {
        this.goodsStocks = goodsStocks;
        this.goodsStockMapper = goodsStockMapper;
    }

    /**
     * 更新商品库存
     */
    @Override
    public Boolean updateGoodsStock() {
        try {
            updateSaleStockQuantity();
            updateLockedStockQuantity();
            updateSaledStockQuantity();

            executeUpdateGoodsStock();
            executeUpdateWarehouseGoodsStock();
            executeUpdateGoodsStockLog();
        } catch (Exception e) {
            logger.error("error", e);
        }
        return true;
    }

    /**
     * 更新商品的销售库存
     *
     * @throws Exception
     */
    protected abstract void updateSaleStockQuantity() throws Exception;

    /**
     * 更新商品的锁定库存
     *
     * @throws Exception
     */
    protected abstract void updateLockedStockQuantity() throws Exception;

    /**
     * 更新商品的已销售库存
     *
     * @throws Exception
     */
    protected abstract void updateSaledStockQuantity() throws Exception;

    /**
     * 实际执行更新商品库存的操作
     *
     * @throws Exception
     */
    private void executeUpdateGoodsStock() throws Exception {
        for (GoodsStockDO goodsStock : goodsStocks) {
            goodsStock.setUpdateTime(LocalDateTime.now());
            goodsStockMapper.updateById(goodsStock);
        }
    }

    /**
     * 实际执行更新商品分仓库存的操作
     *
     * @throws Exception
     */
    protected abstract void executeUpdateWarehouseGoodsStock() throws Exception;

    /**
     * 实际执行更新商品库存流水的操作
     *
     * @throws Exception
     */
    protected abstract void executeUpdateGoodsStockLog() throws Exception;
}
